﻿using BootstrapBlazor.Components;
using CodeMan.Application.Contracts.ClassGens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeMan.Data.DataServiceBaseExts
{
    /// <summary>
    /// 实体类扩展
    /// 用于数据新增，修改，删除服务
    /// </summary>
    public static class ClassGenDTOExts
    {
        public static bool Query<TModel>(this ClassGenDTO model, IEnumerable<TModel> items)
        {
            if (!string.IsNullOrEmpty(model.Name)) items = items.Cast<ClassGenDTO>().Where(item => item.Name?.Contains(model.Name, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            if (!string.IsNullOrEmpty(model.Desc)) items = items.Cast<ClassGenDTO>().Where(item => item.Desc?.Contains(model.Desc, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            var isSearched = !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Desc);

            return isSearched;
        }

        public static bool Save<TModel>(this ClassGenDTO model, List<TModel> Items)
            where TModel : class, new()
        {
            var item = Items?.FirstOrDefault(item =>
            {
                var f = item as ClassGenDTO;
                return f.Name == model.Name;
            });
            if (item == null)
            {
                Int64 id = Items!.Count() + 1;
                while (Items.FirstOrDefault(item => (item as ClassGenDTO)!.Id == id) != null)
                {
                    id++;
                }
                item = new ClassGenDTO()
                { 
                    Name = model.Name,
                    Desc = model.Desc,
                    Type = model.Type,
                    Complete = model.Complete


                } as TModel;
                Items?.Add(item!);
            }
            else
            {
                var f = item as ClassGenDTO;
                f.Name = model.Name;
                f.Desc = model.Desc;
                f.Type = model.Type;
                f.Complete = model.Complete;
            }
            return true;
        }
    }
}
